Page({
  data: {
    userInfo: {
      nickName: '海大力',
      avatarUrl: ''
    },
    userId: '666',
    completedSurveys: 12,
    sleepReports: 8,
    averageScore: 85,
    deviceNo: '',
    managerName: '',
    isDeviceActive: true,
    deviceInfo: null
  },

  onLoad() {
    this.getUserInfo()
    this.getDeviceInfo()
  },

  onShow() {
    this.getStatistics()
    this.loadDeviceInfo()
  },

  // 获取用户信息
  getUserInfo() {
    // TODO: 从本地存储或服务器获取用户信息
    const userInfo = wx.getStorageSync('userInfo') || this.data.userInfo
    this.setData({ userInfo })
  },

  // 获取统计数据
  getStatistics() {
    // TODO: 调用获取统计数据的API
    // 这里使用模拟数据
    this.setData({
      completedSurveys: 12,
      sleepReports: 8,
      averageScore: 85
    })
  },

  // 切换底部导航
  switchTab(e) {
    const page = e.currentTarget.dataset.page
    wx.switchTab({
      url: `/pages/${page}/index/index`
    })
  },

  getDeviceInfo() {
    // TODO: 从本地存储或服务器获取设备信息
    const deviceInfo = wx.getStorageSync('deviceInfo');
    if (deviceInfo) {
      this.setData({
        deviceNo: deviceInfo.deviceNo,
        managerName: deviceInfo.managerName
      });
    }
  },

  loadDeviceInfo() {
    const deviceInfo = wx.getStorageSync('deviceInfo');
    this.setData({ deviceInfo });
  },

  onViewDevice() {
    // 查看设备详情
    wx.navigateTo({
      url: '/pages/device/detail/index'
    });
  },

  onScanQRCode() {
    wx.navigateTo({
      url: '/pages/device/bind/index'
    });
  },

  onInputDevice() {
    wx.navigateTo({
      url: '/pages/device/bind/index'
    });
  },

  onUnbindDevice() {
    wx.showModal({
      title: '解除绑定',
      content: '确定要解除设备绑定吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除设备信息
          wx.removeStorageSync('deviceInfo');
          this.setData({ deviceInfo: null });
          wx.showToast({
            title: '已解除绑定',
            icon: 'success'
          });
        }
      }
    });
  },

  onChangeDevice() {
    wx.navigateTo({
      url: '/pages/device/bind/index'
    });
  },

  onNavigate(e) {
    const { url } = e.currentTarget.dataset;
    wx.navigateTo({ url });
  },

  // 底部导航处理函数
  onTabChange(e) {
    const page = e.currentTarget.dataset.page;
    if (page === 'survey') {
      wx.redirectTo({
        url: '/pages/survey/index/index'
      });
    } else if (page === 'report') {
      wx.redirectTo({
        url: '/pages/report/list/index'
      });
    } else {
      wx.switchTab({
        url: `/pages/${page}/index/index`
      });
    }
  }
}) 